package com.maiyuren.fishkit.ui.pages.main

import android.content.Context
import android.view.inputmethod.InputMethodManager
import androidx.compose.runtime.mutableStateOf
import androidx.compose.ui.unit.sp
import androidx.navigation.NavHostController
import com.maiyuren.fishkit.history.FavouriteManager
import com.maiyuren.fishkit.ui.components.FishMenuItem
import com.maiyuren.fishkit.ui.components.dict.FishDictViewModel
import com.maiyuren.fishkit.ui.route.MainActivity
import com.maiyuren.fishkit.ui.route.RoutePath
import com.maiyuren.fishkit.utils.FishAlertUtils
import com.maiyuren.fishkit.utils.FishEvent
import com.maiyuren.fishkit.utils.FishEventBus
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import java.util.Timer
import java.util.TimerTask
import kotlin.random.Random


//val flow = MutableStateFlow(index)
//GlobalScope.launch(Dispatchers.Main) {
//    flow.collect {
//        it.value.toString().logD("cc")
//        it.value = 3;
//    }
//}



//    class MyTimerTask(val i: MutableState<Int>): TimerTask() {
//        override fun run() {
//            i.value.toString().logD();
//        }
//    }
//
//    Timer().schedule(MyTimerTask(index), 0, 1000)


internal class MainPageViewModel : FishDictViewModel() {
    val toSearchText = mutableStateOf("")
    var showHistoryUI = mutableStateOf(false)
    var showMainMenu = mutableStateOf(false)
    var showRandomUI = mutableStateOf(false)
    var navController: NavHostController? = null
    var isCurrSearchWordFavourite = mutableStateOf(false)
    var isCurrFound = mutableStateOf(false)
    var currFoundWord = mutableStateOf("")
    val mainMenu: List<FishMenuItem> = listOf(
//        FishMenuItem(
//            title = "設定",
//            icon = "\uE864",
//            onClick = {}
//        ),

//        FishMenuItem(
//            title = "我的書架",
//            icon = "\uE631",
//            onClick = {}
//        ),
//        FishMenuItem(
//            title = "網路資源",
//            icon = "\uE7DF",
//            onClick = {}
//        ),
        FishMenuItem(
            title = "收藏本",
            icon = "\uE634",
            iconSize = 20.sp,
            onClick = {
                navController?.navigate(RoutePath.FAVOURITE)
            }
        ),
//        FishMenuItem(
//            title = "編碼查字",
//            icon = "\uE63B",
//            onClick = {}
//        ),
        FishMenuItem(
            title = "因緣會字",
            icon = "\uE6FD",
            onClick = {
                showRandomUI.value = true
                goRandomWord()
            }
        ),
    )

    init {
        FishEventBus.on(FishEvent.goWord) {
            val word = it as String?
            if (word != null) {
                toSearchText.value = word
                onSearch()
            }
        }

        FishEventBus.on(FishEvent.searchResult) {
            val word = it as String?
            if (word != null) {
                isCurrFound.value = true
                currFoundWord.value = word
                isCurrSearchWordFavourite.value = FavouriteManager.instance().isWordInFavorite(word!!)
            } else {
                isCurrSearchWordFavourite.value = false
                isCurrFound.value = false
            }
        }

        FishEventBus.on(FishEvent.clearFavourite) {
            isCurrSearchWordFavourite.value = false
        }
    }

    fun hideKeyboard() {
        val imm = MainActivity.instance?.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
        if (MainActivity.instance?.currentFocus?.windowToken != null) {
            imm.hideSoftInputFromWindow(MainActivity.instance?.currentFocus!!.windowToken, 0)
        }
    }

    fun onSearch(force: Boolean = true) {
        this.search(this.toSearchText.value, force = force)
        hideKeyboard()
    }

    fun delaySearch(ms: Int) {
        val timer = Timer()
        val timerTask = object : TimerTask(){
            override fun run() {
                timer.cancel()
                GlobalScope.launch(Dispatchers.Main) {
                    onSearch()
                }
            }
        }
        timer.schedule(timerTask, ms.toLong(), ms.toLong())
    }

    fun goRandomWord() {
        val dict = getCurrDict()
        if (dict.isWeb()) {
            FishAlertUtils.toast("網路辭典暫不支援因緣會字哦")
            return
        }
        val intWord = Random.nextInt(1, dict.getCount() + 1)
        toSearchText.value = intWord.toString()
        onSearch()
    }
}